Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

321
Visualizações
How to get current datetime seperated by a dash "-" in JS?

I'm trying to construct a nice file name. I tried to do it in 1 line in JS, but have not found anything yet. So I did these

const date = new Date().toLocaleDateString().replaceAll('/', '-').replaceAll('_', '-').replaceAll(' ', '-');
const time = new Date().toLocaleTimeString().replaceAll('/', '-').replaceAll('_', '-').replaceAll(' ', '-');
let dateTime = date + '-' + time;
console.log(dateTime);

I got

6-24-2022-3_38_18-PM

Why is the 2x _ underscores still there ??

GOAL

I'm trying to get

6-24-2022-3-33-17-PM

Do you guys know a better way to achieve that ?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

const date = new Date().toLocaleDateString().replaceAll('/', '-').replaceAll('_', '-').replaceAll(' ', '-')
const time = new Date().toLocaleTimeString().replaceAll('/', '-').replaceAll('_', '-').replaceAll(' ', '-')
console.log(date + '-' + time)

I see almost your desired result: 6-24-2022-3:48:11-PM (since you did not change : (colon) in time.

about 4 years ago · Juan Pablo Isaza Relatório

0

better way to achieve that, instead use Moment.js

The format() method returns the date in specific format.

moment(new Date()).format("DD-MM-YYYY-hh-mm-ss-A");

NOTE: "A"-> 12H clock (AM/PM)

about 4 years ago · Juan Pablo Isaza Relatório

0

Why is the 2x _ underscores still there ??

You are likely replacing something that isn't actually an underscore

Do you guys know a better way to achieve that?

Yes. Try using a RegExp

const date = new Date().toLocaleDateString().replace(/[^apm\d]+/gi, '-')
const time = new Date().toLocaleTimeString().replace(/[^apm\d]+/gi, '-')
let dateTime = date + '-' + time

console.log(dateTime)

This will remove anything that is not ([^...]+) an a p m or digit (\d).

/.../gi are the flags global and case-insensitive.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda